package com.msw.json;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONWriter;
import org.junit.Test;

import java.io.FileWriter;

public class FastJsonUtil {

    /**
     * fastjson提供的json writer
     *
     * @throws Exception
     */
    @Test
    public void jsonWriter() throws Exception {
        JSONWriter writer = new JSONWriter(new FileWriter("test.json"));
        writer.startObject();
        writer.writeKey("customerId");
        writer.writeValue("xxxxxxxxxxxx");
        writer.writeKey("resources");
        writer.startObject();
        writer.writeKey("resourceId");
        writer.writeValue("yyyyyyy");
        writer.endObject();
        writer.endObject();
        writer.flush();
        writer.close();
    }


    /**
     * 基于JsonObject来实现的动态拼接json string
     *
     * @throws Exception
     */
    @Test
    public void jsonGenerate() throws Exception
    {
        JSONObject root = new JSONObject(true);
        root.fluentPut("resourceId", "xxxxxxxxx")
                .fluentPut("customers", new JSONObject().fluentPut("customerId", "xxxxxxxx"));

        System.out.println(root.toJSONString());
    }
}
